import { getToken } from './auth'
const baseUrl = 'https://api-hmugo-web.itheima.net/api/public/v1'
let count = 0
const service = ({ url, method, data, header, dataType }, hideLoading) => {
  ;(method = method ? method : 'GET'), (dataType = dataType ? dataType : 'json')
  count++
  //接口请求
  if (!hideLoading) {
    wx.showLoading({
      mask: true,
      title: '请稍候...'
    })
  }
  return new Promise((resolve, reject) => {
    wx.request({
      url: baseUrl + url,
      data: data,
      header: {
        'content-type': 'application/json',
        Authorization: getToken(),
        ...header
      },
      method: method.toUpperCase(), //'GET','POST'
      dataType,
      success: (res) => {
        const meta = res.data.meta
        console.log(res)
        if (meta.status !== 200) {
          wx.showToast({
            title: meta.msg,
            icon: 'none',
            duration: 2000
          })
          reject(res)
        } else {
          resolve(res)
        }
      },
      fail: (err) => {
        if (!hideLoading) {
          wx.showToast({
            title: '网络不给力,请稍后再试~',
            icon: 'none',
            duration: 2000
          })
        }
        reject(err)
      },
      complete: () => {
        count--
        !hideLoading && count === 0 && wx.hideLoading()
      }
    })
  })
}

export default service
